<template>
  <div>
    <el-dialog
      :model-value="props.dialogVisible"
      title="角色权限"
      width="500px"
      :close-on-click-modal="false"
      :before-close="handleClose">
      <el-tree
        ref="treeRef"
        :data="treeData"
        :expand-on-click-node="false"
        show-checkbox
        default-expand-all
        node-key="id"
        highlight-current
        :props="defaultProps"
      />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="RoleAuthDialog">
import { ref, reactive, watch, ComponentInternalInstance, getCurrentInstance, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import NAV from '@/config/navs'
import { roleUpdate } from '@/api/role-manage'

const { proxy } = getCurrentInstance() as ComponentInternalInstance

const emit = defineEmits(['submit', 'update:dialogVisible'])
const props = defineProps({
  dialogVisible: {
    type: Boolean,
    default: false
  },
  formData: {
    type: Object,
    default: {}
  }
})

const defaultProps = {
  children: 'children',
  label: 'title',
}
const treeRef = ref<any>(null)
const treeData = ref<any>([])
const roleForm = reactive({
  roleId: -1,
  // power: ''
})

watch(() => props.dialogVisible, async (newVal) => {
  if (newVal) {
    treeData.value = [...NAV]
    roleForm.roleId = props.formData.roleId
    // roleForm.power = props.formData.power
    nextTick(() => {
      formatMenuAuth()
    })
  }
})

// 解析原有菜单
const formatMenuAuth = () => {
  if (props.formData.power) {
    let menu = JSON.parse(props.formData.power)
    let selected = <any>[]
    menu.map((item: any) => {
      selected.push(item.id)
      item.children.map((cl: any) => {
        selected.push(cl.id)
      })
    })
    let arr = <any>[]
    NAV.map((item: any) => {
      if (selected.indexOf(item.id) !== -1) {
        if (item.children.length !== 0) {
          item.children.map((cl: any) => {
            if (selected.indexOf(cl.id) !== -1) {
              arr.push(cl.id)
            }
          })
        } else {
          arr.push(item.id)
        }
      }
    })
    treeRef.value.setCheckedKeys(arr)
  }
}

// 过滤出传参格式菜单
const filterMenuAuth = () => {
  let arr = <any>[]
  let selected = treeRef.value.getCheckedKeys().concat(treeRef.value.getHalfCheckedKeys())
  NAV.map((item: any) => {
    if (selected.indexOf(item.id) !== -1) {
      let obj = {
        id: item.id,
        title: item.title,
        index: item.index,
        icon: item.icon,
        children: <any>[]
      }
      item.children.map((cl: any) => {
        if (selected.indexOf(cl.id) !== -1) {
          obj.children.push(cl)
        }
      })
      arr.push(obj)
    }
  })
  return arr
}

// 关闭弹窗
const handleClose = () => {
  proxy?.$emit('update:dialogVisible', false)
}

// 提交表单
const handleSubmit = async () => {
  let arr = filterMenuAuth()
  let params = {
    roleId: roleForm.roleId,
    power: arr.length === 0 ? '' : JSON.stringify(arr)
  }
  await roleUpdate(params).then((res: any) => {
    if (res.code === 0) {
      ElMessage.success(`编辑成功！`)
      emit('submit')
      handleClose()
    } else {
      ElMessage.error(`${res.msg}`)
    }
  }).catch(err => {
    console.log(err)
  })
}
</script>

<style lang="stylus" scoped>

</style>
